﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PhenoType : MonoBehaviour
{
    private List<GameObject> parts = new List<GameObject>();
    private GameObject parent;
    private Vector3 lastPosition;

    private Vector3 startPosition;

    float distance = 0;

    public float Fitness = 0.0f;
    //Returns the size of the Wackimal - needed to remove too small or too large Wackimals
    public int Parts { get { return parts.Count; } private set {} }

    private bool ready = false;

    public void Init(string axiom)
    {
        StartCoroutine(InitWackimal(axiom));
    }

    IEnumerator InitWackimal(string axiom)
    {
        //send list as reference so we can handle it in out static Wackimal class
        Wackimals.Instance.Create(axiom, ref parts);
        yield return new WaitForEndOfFrame();

        //Make sure we actually got a wackimal with body parts
        if (parts.Count > 0)
        {
            parent = parts[0];

            yield return new WaitForSeconds(1.0f);

            lastPosition = parent.transform.position;
            startPosition = parent.transform.position;
            ready = true;
        }
        else
        {
            Debug.Log("Error, wackimal with not parts!!");
        }
    }

    void FixedUpdate()
    {
        if (parent != null && ready)
        {
            distance = Vector3.Distance(parent.transform.position, startPosition);
            lastPosition = parent.transform.position;

            if (distance > Fitness)
                Fitness = distance;
        }
    }

    public List<GameObject> GetParts()
    {
        return parts;
    }

    public float GetFitness()
    {
        //float dist = Vector3.Distance(transform.position, startPosition);
       // print("Distance: " + dist);
        //Fitness += dist * dist;

        return Fitness;
    }

    public void DestroyWackimal()
    {
        if (parts.Count > 0)
        {
            foreach (GameObject part in parts)
            {
                Destroy(part);
            }
            parts.Clear();
        }
    }
}
